<template>
  <div>
    <section class="scroll-container">
      <div class="scroll-element js-scroll fade-in">1</div>
      <div class="scroll-caption">淡入动效</div>
    </section>
    <section class="scroll-container">
      <div class="scroll-element js-scroll fade-in-bottom">2</div>
      <div class="scroll-caption">切入顶部动效</div>
    </section>
    <section class="scroll-container">
      <div class="scroll-element js-scroll slide-left">3</div>
      <div class="scroll-caption">从左边切入动效</div>
    </section>
    <section class="scroll-container">
      <div class="scroll-element js-scroll slide-right">4</div>
      <div class="scroll-caption">从右边切入动效</div>
    </section>
  </div>
</template>

<script>
export default {
  name: 'scrollAnimation',
  data() {
    return {
      scrollElements: null
    };
  },
  mounted() {
    this.scrollElements = document.querySelectorAll('.js-scroll');
    window.addEventListener('scroll', () => {
      this.handleScrollAnimation();
    });
  },
  methods: {
    elementInView(el, percentageScroll = 100) {
      const elementTop = el.getBoundingClientRect().top;
      return (
        elementTop <=
        (window.innerHeight || document.documentElement.clientHeight) *
          (percentageScroll / 100)
      );
    },
    displayScrollElement(element) {
      element.classList.add('scrolled');
    },
    hideScrollElement(element) {
      element.classList.remove('scrolled');
    },
    handleScrollAnimation() {
      this.scrollElements.forEach(el => {
        if (this.elementInView(el, 100)) {
          this.displayScrollElement(el);
        } else {
          this.hideScrollElement(el);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.scroll-container {
  height: 100vh;
}
.scroll-element {
  width: 300px;
  height: 300px;
  background-color: #586c94;
}
.js-scroll {
  opacity: 0;
  transition: opacity 500ms;
  &.scrolled {
    opacity: 1;
  }
}
.scrolled.fade-in {
  animation: fade-in 1s ease-in-out both;
}

.scrolled.fade-in-bottom {
  animation: fade-in-bottom 1s ease-in-out both;
}

.scrolled.slide-left {
  animation: slide-in-left 1s ease-in-out both;
}

.scrolled.slide-right {
  animation: slide-in-right 1s ease-in-out both;
}

@keyframes slide-in-left {
  0% {
    transform: translateX(-100px);
    opacity: 0;
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slide-in-right {
  0% {
    transform: translateX(100px);
    opacity: 0;
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes fade-in-bottom {
  0% {
    transform: translateY(50px);
    opacity: 0;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fade-in {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>
